package com.hqhsc.module.manage.system.dao;

import com.hqhsc.core.dao.BaseJdbcDaoImpl;
import com.hqhsc.module.common.dao.CommonDao;
import com.hqhsc.module.login.domain.User;
import com.hqhsc.module.login.domain.UserRowMapper;
import com.hqhsc.module.manage.system.domain.Org;
import com.hqhsc.module.manage.system.domain.OrgRowMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


@Repository
public class SystemManageDao extends BaseJdbcDaoImpl {
	final Logger logger = LoggerFactory.getLogger(SystemManageDao.class);

    @Autowired
    private CommonDao commonDao;

    public long getUserCount(long org_id , String user_name) {
        String sql = "select count(1) from users t , user_role a where t.user_id = a.user_id and a.role_id > 10000 ";
        List<Object> list = new ArrayList<Object>();
        if(StringUtils.isNotEmpty(user_name)) {
            sql = sql + " and user_name like ? ";
            list.add("%"+user_name+"%");
        }
        Object[] o = list.toArray();
        logger.info(sql.replaceAll("\\?", "{}"), o);
        return this.getJdbcTemplate().queryForLong(sql, o);
    }


    public List<User> getUserList(long org_id , String user_name , int start ,  int size) {

        String sql = "select t.* , b.org_name , c.role_name " +
                "from users t , user_role a , sys_org b , sys_roles c " +
                "where t.user_id = a.user_id and a.org_id = b.org_id and a.role_id = c.role_id and a.role_id > 10000 ";
        List<Object> list = new ArrayList<Object>();
        if(StringUtils.isNotEmpty(user_name)) {
            sql = sql + " and t.user_name like ? ";
            list.add("%"+user_name+"%");
        }
        list.add(start);
        list.add(size);
        Object[] o = list.toArray();
        sql = sql + " limit ? ,? ";
        logger.info(sql.replaceAll("\\?", "{}"), o);
        return this.getJdbcTemplate().query(sql, o, new UserRowMapper());
    }


    /**
     * 登录名不能重复
     * @param login_name
     * @return 0-没有该登录名；1-有
     */
    public int checkUserName(String login_name) {
        String sql = "select count(1) from users where login_name = ?";
        Object[] o = new Object[] { login_name };
        logger.info(sql.replaceAll("\\?", "{}"), o);
        return this.getJdbcTemplate().queryForInt(sql, o);
    }

    /**
     * 增加用户
     * @param login_name
     * @param login_pwd
     * @param user_name
     * @param nick_name
     * @param create_by
     * @param create_at
     * @return
     */
    public int inertUser(long userid , String login_name , String login_pwd , String user_name , String nick_name , long create_by , String create_at , String employee_id) {
        String sql = "insert into users (user_id , login_name , login_pwd , user_name , nick_name , create_by , create_at , employee_id) values (?,?,?,?,?,?,?,?)";
        Object[] o = new Object[] { userid , login_name , login_pwd , user_name , nick_name , create_by , create_at , employee_id };
        logger.info(sql.replaceAll("\\?", "{}"), o);
        return this.getJdbcTemplate().update(sql, o);
    }

    /**
     * 增加用户组织角色
     * @param userid
     * @param role_id
     * @param org_id
     * @return
     */
    public int insertUserRole(long userid , long role_id , long org_id) {
        String sql = "insert into user_role (user_id , role_id , org_id) values (?,?,?)";
        Object[] o = new Object[] { userid , role_id , org_id };
        logger.info(sql.replaceAll("\\?", "{}"), o);
        return this.getJdbcTemplate().update(sql , o);
    }

    /**
     * 编辑用户
     * @param edit_user_id
     * @param user_name
     * @param userid
     * @return
     */
    public int editUser(long edit_user_id , String user_name , long userid , String employee_id , String nick_name) {
        String sql = "update users t set t.user_name = ? , employee_id = ? , nick_name = ?" +
                " where t.user_id = ? and status = 1";
        Object[] o = new Object[] { user_name , employee_id , nick_name , edit_user_id };
        logger.info(sql.replaceAll("\\?", "{}"), o);
        return this.getJdbcTemplate().update(sql , o);
    }


    /**
     * 删除用户
     * @param deleted_user_id
     * @return
     */
    public int deleteUser(long deleted_user_id) {
        String sql = "update users t set t.status = 0 where t.user_id = ?";
        Object[] o = new Object[] { deleted_user_id };
        logger.info(sql.replaceAll("\\?", "{}"), o);
        return this.getJdbcTemplate().update(sql , o);
    }


    public long getOrgCount(String org_name) {
        String sql = "select count(1) from sys_org t where 1=1 ";
        List<Object> list = new ArrayList<Object>();
        if(StringUtils.isNotEmpty(org_name)) {
            sql = sql + " and org_name = ? ";
            list.add(org_name);
        }
        Object[] o = list.toArray();
        logger.info(sql.replaceAll("\\?", "{}"), o);
        return this.getJdbcTemplate().queryForLong(sql, o);
    }


    public List<Org> getOrgList(String user_name , int start ,  int size) {

        String sql = "select * from sys_org t where status = 1 ";
        List<Object> list = new ArrayList<Object>();
        if(StringUtils.isNotEmpty(user_name)) {
            sql = sql + " and t.org_name = ? ";
            list.add(user_name);
        }
        list.add(start);
        list.add(size);
        Object[] o = list.toArray();
        sql = sql + " limit ? ,? ";
        logger.info(sql.replaceAll("\\?", "{}"), o);
        return this.getJdbcTemplate().query(sql, o, new OrgRowMapper());
    }

    public int orgDoAdd(String org_name , String org_address , long user_id) {
        long org_id = this.commonDao.getNextVal("OrgSeq");

        String sql = "insert into sys_org (org_id , org_name , org_address , create_by) values (?,?,?,?)";
        Object[] o = new Object[] { org_id , org_name , org_address , user_id };
        logger.info(sql.replaceAll("\\?", "{}"), o);
        return this.getJdbcTemplate().update(sql , o);
    }



    public void deleteRoleMenu(long role_id) {
        String sql = "delete from sys_role_menu where role_id = ?";
        Object[] o = new Object[] { role_id };
        logger.info(sql.replaceAll("\\?", "{}"), o);
        this.getJdbcTemplate().update(sql, o);
    }

    public void roleMenuDoConfig(final String[] all_menu_ids , final long role_id) {
        this.deleteRoleMenu(role_id);
        String sql = "insert into sys_role_menu (role_id , menu_id) values (?,?)";
        try {
            this.getJdbcTemplate().batchUpdate(sql, new BatchPreparedStatementSetter() {
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    ps.setLong(1, role_id);
                    ps.setLong(2, Long.valueOf(all_menu_ids[i]));
                }
                public int getBatchSize() {
                    return all_menu_ids.length;
                }
            });
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }


    public int doResetPassword(long modify_user_id , String password) {
        String sql = "update users set login_pwd = ? where user_id = ? and status = 1 ";
        Object[] o = new Object[] { password ,  modify_user_id};
        logger.info(sql.replaceAll("\\?", "{}"), o);
        return this.getJdbcTemplate().update(sql , o);
    }
}
